package com.wy.office.swift;

import java.io.Closeable;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.wy.office.swift.exception.OfficeSwiftException;
import com.wy.office.swift.util.StringUtils;

/**
 * 公共抽象类
 * @author wangyuan
 * @since 2019年4月8日 下午11:33:14
 *
 */
public abstract class AOfficeHandler implements IVariableExtractor, IOfficeConstants {
	
	private static final Logger logger = LoggerFactory.getLogger(AOfficeHandler.class);

	@Override
	public List<String> extractVariables(String text) throws OfficeSwiftException {
		List<String> variableList = new ArrayList<>();
		if (StringUtils.checkParamIsEmpty(text)) {
			logger.debug("参数 text 为空，不做处理，返回空集合。");
			return variableList;
		}

		// 临时存放变量容器
		Set<String> variableSet = new HashSet<>();
		
		Pattern pattern = Pattern.compile(VARIABLE_REGEX);
		Matcher matcher = pattern.matcher(text);
		String matchStr = null;
		while (matcher.find()) {
			matchStr = matcher.group();
			matchStr = matchStr.substring(VARIABLE_PREFIX.length(), matchStr.length() - VARIABLE_SUFFIX.length());
			if (StringUtils.isNotEmpty(matchStr)) {
				variableSet.add(matchStr);
			}
		}
		
		variableList.addAll(variableSet);

		return variableList;
	}

	protected void closeResource(Closeable close) {
		try {
			if (close != null) {
				close.close();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
